package com.itheima.filter;


import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.utile.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;

        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String uri = req.getRequestURI();

        /*
        表示可以访问的页面
         */
        if (uri.endsWith(".js") || uri.contains("images")|| uri.contains("plugins")
                || uri.contains("styles") || uri.contains("fonts") || uri.endsWith(".ico") || uri.contains("login")
                || uri.contains("code")) {

            filterChain.doFilter(servletRequest, servletResponse);

            return;

        }

        /*
        表示已经登入过的页面
         */
            Employee employee = (Employee) req.getSession().getAttribute("Employee");

            if (employee != null) {

                BaseContext.setThreadLocal(employee.getId());

                filterChain.doFilter(servletRequest, servletResponse);

                return;

            }

            User user = (User) req.getSession().getAttribute("user");

            if (user != null) {

                BaseContext.setThreadLocal(user.getId());

                filterChain.doFilter(servletRequest, servletResponse);

                return;
            }

        if (uri.contains("backend")) {
            //表示访问地址都不可以就得跳入到登入页面
            resp.sendRedirect("/backend/page/login/login.html");

        }

        if (uri.contains("front")){

            resp.sendRedirect("/front/page/login.html");

        }

    }
}
